package com.yzt.message.conversation;

import static com.yzt.message.MessageConstants.TYPE_ACCOUNT_SYSTEM;
import static com.yzt.message.MessageConstants.TYPE_INTERACTIVE_MESSAGE;

import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.yzt.zhuju.network.entity.message.CompanyNoticeData;
import com.yzt.zhuju.rongyun.IMMessageType;
import com.yzt.p_base.AppUtils;
import com.yzt.message.util.UserInfoManager;
import com.yzt.message.R;
import com.yzt.message.custom.BroadcastMessageContent;

import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.model.GatheredConversation;
import io.rong.imkit.conversationlist.model.SingleConversation;
import io.rong.imlib.model.Conversation;
import io.rong.message.TextMessage;

/**
 * 自定义处理消息，涉及数据排序
 */
public class CustomConversationReceiptHandler implements IReceiptHandler {

    final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,
            Integer.MAX_VALUE,
            3,
            TimeUnit.SECONDS,
            new SynchronousQueue<>());

    private int handleData = 0;

    @Override
    public List<BaseUiConversation> handleReceipt(List<BaseUiConversation> uiConversations) {

        handleData++;

        Log.e("自定义处理消息，涉及数据排序", "自定义处理消息，涉及数据排序---->" + handleData);

        if (uiConversations == null || uiConversations.isEmpty()) {
            return null;
        }

        threadPoolExecutor.purge();

        int passiveTopIndex = 0;

        //系统公告记录
        BaseUiConversation officeNoticeConversation = null;

        for (BaseUiConversation mUiConversation : uiConversations) {

            Conversation mConversation = mUiConversation.mCore;
            String senderUserId = mConversation.getSenderUserId();

            String targetId = mConversation.getTargetId();
            boolean isPassiveTop = UserInfoManager.getInstance().isTopPrivilegeUser(targetId)
                    && (!TYPE_INTERACTIVE_MESSAGE.equals(targetId))
                    && (!TYPE_ACCOUNT_SYSTEM.equals(targetId))
                    && !(mUiConversation instanceof GatheredConversation);
            if (isPassiveTop) {
                uiConversations.remove(mUiConversation);
                uiConversations.add(passiveTopIndex, mUiConversation);
                passiveTopIndex++;
            }

            //-------------------------------------
            // 记录是否存在及系统公告，如果不存在，要手动创建消息并加入
            // 系统公告del 尝试走一下系统消息
            if (senderUserId.equals(TYPE_ACCOUNT_SYSTEM)) {
                officeNoticeConversation = mUiConversation;
                uiConversations.remove(mUiConversation);
            }
        }

        /*
         *  加载官方公告
         * todo 官方公告
         */
        if (officeNoticeConversation == null) {
            Conversation conversation = Conversation.obtain(Conversation.ConversationType.PRIVATE, TYPE_ACCOUNT_SYSTEM, "官方公告");
            conversation.setSenderUserId(TYPE_ACCOUNT_SYSTEM);
            conversation.setTargetId(TYPE_ACCOUNT_SYSTEM);
            TextMessage mTextMessage = TextMessage.obtain(AppUtils.getApp().getString(R.string.official_announcement));
            conversation.setLatestMessage(mTextMessage);
            conversation.setObjectName(IMMessageType.SERVER_NOTICE_MESSAGE);
            officeNoticeConversation = new SingleConversation(ReceiptHandlerContainer.mContext, conversation);
        } else {
            if (officeNoticeConversation.mCore.getLatestMessage() instanceof BroadcastMessageContent) {
                try {
                    String extra = officeNoticeConversation.mCore.getLatestMessage().getExtra();
                    CompanyNoticeData mCompanyNoticeData = JSON.parseObject(extra, CompanyNoticeData.class);
                    TextMessage mTextMessage = TextMessage.obtain(mCompanyNoticeData.getTitle());
                    officeNoticeConversation.mCore.setLatestMessage(mTextMessage);
                    officeNoticeConversation.onConversationUpdate(officeNoticeConversation.mCore);
                    if (!TextUtils.isEmpty(mCompanyNoticeData.getTitle())) {
                        officeNoticeConversation.mConversationContent = new SpannableString(mCompanyNoticeData.getTitle());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (officeNoticeConversation.mCore.getLatestMessage() instanceof TextMessage) {
                TextMessage mTextMessage = (TextMessage) officeNoticeConversation.mCore.getLatestMessage();
                if (!TextUtils.isEmpty(mTextMessage.getContent())) {
                    officeNoticeConversation.mConversationContent = new SpannableString(mTextMessage.getContent());
                }
            }
        }

        // 加入官方公告,并处理content数据，官方公告默认第一个位置
        officeNoticeConversation.mCore.setTop(true);
        uiConversations.add(0, officeNoticeConversation);
        return uiConversations;
    }
}